<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Hcomic Creator</title>
    <script src="/asset/vue.js"></script>
    <script src="/asset/iview.min.js"></script>
    <link rel="stylesheet" href="/asset/iview.css">
    <style>
        html, body {
            padding: 0;
            margin: 0;
            width: 100%;
            font-size: 14px;
        }

        body {
            background: url(/asset/bg.jpg) center top;
            position: relative;
            width: 100%;
            height: 100%;
        }

        .form {
            width: 35%;
        }

        .container {
            display: flex;
            justify-content: center;
            margin-top: 3%;
            margin-left: 25%;
        }

        #app {
            width: 100%;
            height: 100%;
        }

        .button {
            width: 100%;
        }

        .ivu-form-item {
            margin-bottom: 15px;
        }

        .ivu-alert-with-banner {
            display: flex;
            justify-content: center;
        }

        .title {
            position: absolute;
            margin-left: 1%;
            font-size: 2.9rem;
            color: whitesmoke;
            margin-top: 30px;
        }

        .title a {
            color: whitesmoke;
        }

        @media (orientation: portrait) {
            body {
                background: url(/asset/mobile-gb.jpg) center top;
            }
            #app {
                display: flex;
                flex-direction: column;
            }

            .title {
                position: unset;
                margin-left: 6rem;
                font-size: 6rem;
            }
            .title a {
                color: darkgrey;
            }

            .container {
                justify-content: center;
                margin-top: 30rem;
                margin-left: -5rem;
            }

            .ivu-form-item {
                margin-bottom: 3rem;
                font-size: 5.5rem;
            }

            .form {
                width: 85%;
            }

            .ivu-btn, .ivu-input {
                font-size: 2.5rem;
                height: 4.5rem;
            }
        }
    </style>
</head>

<body>
<div id="app">
    <h1 class="title">
        <a href="https://github.com/ystyle/kas" target="_blank" title="查看源码">Hcomic Creator</a>
    </h1>
    <Alert banner closable v-if="connectState == 'closed'" type="warning">
        与服务器断开连接, 等待重新连接, 请稍等...
    </Alert>
    <div class="container">
        <i-form class="form" :model="formItem" :label-width="80" :rules="ruleValidate" :label-width="0">
            <form-item>
                <i-input v-model="formItem.Url" placeholder="https://c-upp.com/cn/s/xxxxxx/"></i-input>
            </form-item>
            <form-item>
                <i-input v-model="formItem.Bookname" placeholder="漫画显示名称(默认为网页标题)"></i-input>
            </form-item>
            <form-item>
                <i-input v-model="formItem.Author" placeholder="作者(默认kas)"></i-input>
            </form-item>
            <form-item>
                <i-button
                        class="button"
                        :loading="loading"
                        :disabled="connectState != 'connected' || !formItem.Url"
                        type="primary"
                        @click="submit">
                    走你!
                </i-button>
            </form-item>
        </i-form>
        <Drawer width="640" v-model="drawer" :closable="false">
            <Timeline :pending="true">
                <Timeline-item color="green">
                    <div slot="dot"></div>
                    <i-button v-if="logLoading" loading shape="circle" type="primary">请稍等</i-button>
                </Timeline-item>
                <Timeline-item v-for="log in sortedLogs" color="green">
                    <Tag :color="log.type">{{log.msg}}</Tag>
                </Timeline-item>
            </Timeline>
        </Drawer>
    </div>

</div>

<script>
    var loc = window.location;
    var uri = 'ws:';
    if (loc.protocol === 'https:') {
        uri = 'wss:';
    }
    uri += '//' + loc.host;
    uri += loc.pathname + 'ws';

    var app = new Vue({
        el: '#app',
        data: {
            ws: null,
            drawer: false,
            connectState: 'closed',
            loading: false,
            logLoading: false,
            logs: [],
            bookid: '',
            formItem: {
                Url: '',
                Bookname: '',
                Author: ''
            },
            ruleValidate: {
                url: [
                    {required: true, message: '地址不能为空', trigger: 'blur'}
                ]
            }
        },
        computed: {
            sortedLogs: function () {
                return [...this.logs].reverse()
            },
            zipFileName: function () {
                // 生成下载链接
                var zipfile = this.bookid
                if (!zipfile.includes('.zip')) {
                    zipfile += '.zip'
                }
                return zipfile
            }
        },
        methods: {
            submit: function () {
                this.loading = true
                this.drawer = true
                this.logLoading = true
                this.logs = []
                this.formItem.Bookname = this.formItem.Bookname
                this.ws.send(JSON.stringify({
                    Type: "hcomic:submit",
                    Data: this.formItem
                }))
            },
            open: function () {
                console.log('connected')
                this.connectState = 'connected'
            },
            onmessage: function (evt) {
                var msg = JSON.parse(evt.data)
                if (msg.Type === "info") {
                    console.log(msg.Data)
                    this.logs.push({msg: msg.Data, type: 'default'})
                } else if (msg.Type === "Error") {
                    console.error(msg.Data)
                    this.logs.push({msg: msg.Data, type: 'error'})
                    this.logLoading = false
                    this.loading = false
                } else if (msg.Type === "hcomic:bookname") {
                    console.log(msg.Data)
                    this.formItem.Bookname = msg.Data
                    this.logs.push({msg: '标题: ' + msg.Data, type: 'primary'})
                } else if (msg.Type === "hcomic:bookid") {
                    console.log(msg.Data)
                    this.bookid = msg.Data
                    this.logs.push({msg: '解析到ID: ' + msg.Data, type: 'primary'})
                } else if (msg.Type === "hcomic:downloadURL") {
                    console.log('从URL下载', msg.Data)
                    downloadFile(msg.Data, this.zipFileName)
                } else if (msg.Type === "hcomic:download") {
                    console.log('从websocket下载')
                    downloadFileByBase64(msg.Data, this.zipFileName)
                    this.$Message.success({content: '下载成功!'});
                    this.logs.push({msg: '下载成功!', type: 'success', duration: 0})
                    // 清理表单
                    this.formItem.Url = ''
                    this.formItem.Bookname = ''
                    this.formItem.Author = ''
                    // 清理状态
                    this.drawer = false
                    this.loading = false
                    this.logLoading = false
                }
            },
            close: function () {
                this.connectState = 'closed'
                this.loading = false
                this.logLoading = false
            },
            sendclose: function () {
                this.ws.close()
            },
            timer: function () {
                if (this.connectState === 'closed') {
                    this.initWS()
                }
            },
            initWS: function () {
                this.ws = new WebSocket(uri)
                this.ws.onopen = this.open
                this.ws.onmessage = this.onmessage
                this.ws.onclose = this.close
                this.ws.onerror = this.close
            }
        },
        mounted: function () {
            this.initWS()
            window.οnbefοreunlοad = this.sendclose
            setInterval(this.timer, 10 * 1000)
        }
    })

    function dataURLtoBlob(arr) {
        var mime = 'application/x-zip-compressed',
            bstr = atob(arr), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type: mime});
    }

    function downloadFile(url, name = 'What\'s the fuvk') {
        var a = window.document.createElement('a')
        a.href = url
        a.download = name
        a.click()
        window.URL.revokeObjectURL(url)
    }

    function downloadFileByBase64(base64, name) {
        var myBlob = dataURLtoBlob(base64)
        var myUrl = window.URL.createObjectURL(myBlob)
        downloadFile(myUrl, name)
    }
</script>
</body>

</html>